package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linjian.togetherbirthday.MainActivity;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.adapter.base.recyler.ItemWrapper;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerAdapter;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerHolder;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.StoreListBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.util.LogUtil;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.linjian.togetherbirthday.view.citypiker.CityPicker;
import com.linjian.togetherbirthday.view.citypiker.adapter.OnPickListener;
import com.linjian.togetherbirthday.view.citypiker.model.City;
import com.linjian.togetherbirthday.view.citypiker.model.HotCity;
import com.linjian.togetherbirthday.view.citypiker.model.LocateState;
import com.linjian.togetherbirthday.view.citypiker.model.LocatedCity;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class FoodFragment extends BaseFragment implements View.OnClickListener, XRecyclerView.LoadingListener, TextWatcher {

    private RecyclerView foodRecyler;
    private ImageView backIv;
    private TextView titleTv, rightTv;
    private TextView cityTv, regionTv, sortTv, classTv;
    private XRecyclerView mRecyclerView;
    private RecyclerAdapter<StoreListBean.DataBean.RecordsBean> mRecylerAdapter;

    private List<HotCity> hotCities;
    private int anim;
    private boolean enable = true;
    private int checkedbutton = -1;
    private ArrayList<StoreListBean.DataBean.RecordsBean> mList;

    private FrameLayout mDownMuneContainer;
    private Fragment mCurrentFragment;

    private MainActivity activity;

    public static FoodFragment newInstance() {
        FoodFragment foodFragment = new FoodFragment();
        Bundle bundle = new Bundle();
//        bundle.putString("info", info);
        foodFragment.setArguments(bundle);
        return foodFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int setView() {
        return R.layout.fragment_food;
    }

    @Override
    protected void init(View view) {
        activity = (MainActivity)getActivity();

        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);

        mRecyclerView = view.findViewById(R.id.food_recyler);
        cityTv = view.findViewById(R.id.food_city_tv);
        regionTv = view.findViewById(R.id.choose_region);
        mDownMuneContainer = view.findViewById(R.id.down_menu_container);
        classTv = view.findViewById(R.id.food_class_tv);
        sortTv = view.findViewById(R.id.food_sort_tv);

        hotCities = new ArrayList<>();
        hotCities.add(new HotCity("北京", "北京", "101010100"));
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));
        anim = R.style.DefaultCityPickerAnimation;

        FragmentManager fm = getActivity().getSupportFragmentManager();

        // 开启事务
        FragmentTransaction transaction = fm.beginTransaction();

        // 加载左侧
        //                transaction.replace(R.id.down_menu_container, MenuFragmentFactory.getFragment(id));
        /**-----------------------------解决闪烁的问题start--------------------------------------------------**/
        Fragment addressFragment = new PullBaseFragment();
        Fragment catalogueFragment = new CatalogueFragment();
        Fragment sortFragment = new SortFragment();
        transaction.add(R.id.down_menu_container, addressFragment, R.id.choose_region + "");
        transaction.add(R.id.down_menu_container, catalogueFragment, R.id.food_class_tv + "");
        transaction.add(R.id.down_menu_container, sortFragment, R.id.food_sort_tv + "");
        transaction.hide(addressFragment);
        transaction.hide(catalogueFragment);
        transaction.hide(sortFragment);
        transaction.commit();
        /**-----------------------------解决闪烁的问题end--------------------------------------------------**/
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);

        mRecyclerView
                .getDefaultRefreshHeaderView()
                .setRefreshTimeVisible(true);
        mRecyclerView.getDefaultFootView().setLoadingHint("自定义加载中提示");
        mRecyclerView.getDefaultFootView().setNoMoreHint("自定义加载完毕提示");
        mRecyclerView.setLimitNumberToCallLoadMore(1);
        mRecyclerView.setLoadingListener(this);

        mRecylerAdapter = new RecyclerAdapter<StoreListBean.DataBean.RecordsBean>(mItemListener) {
            @Override
            public ItemWrapper getItemHolder(int position) {
                return new ItemWrapper(R.layout.item_food, FoodAdapter.class);
            }
        };
        mRecyclerView.setAdapter(mRecylerAdapter);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        titleTv.setText("美食");
        rightTv.setVisibility(View.GONE);
        httpStoreInfo("深圳", "坂田", "烤鱼", 1);
        setListener();
        httpGetCity("深圳");
    }

    private void setListener() {
        backIv.setOnClickListener(this);
        cityTv.setOnClickListener(this);
        regionTv.setOnClickListener(this);
        sortTv.setOnClickListener(this);
        classTv.setOnClickListener(this);
        cityTv.addTextChangedListener(this);
    }

    private OnItemListener mItemListener = new OnItemListener() {
        @Override
        public void onItemClick(View view, int position,String data) {
            activity.replaceFragment("FoodInfoFragment",data);
        }

        @Override
        public void onItemAddress(View view, String address,String storeName) {
            activity.replaceFragment("ReleaseDateFragment",address+":"+storeName);
        }
    };

    /**
     * 请求店铺信息
     */
    private void httpStoreInfo(String cityName, String region, String category, int page) {
        if (cityName.equals("城市")){
            cityName = "深圳";
        }
        if (region.equals("地区")){
            region = "深大地铁站";
        }
        if (category.equals("分类")){
            category = "菜系";
        }
        HttpUtils.doGet(HttpContant.URL + HttpContant.StoreInfo
                        + "?cityName=" + cityName + "&&region=" + region + "&&category=" + category + "&&page=" + page
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("getStoreInfo", response.body().string()));
                    }
                });
    }

    /**
     * 请求地区商圈数据
     */
    private void httpGetCity(String cityName) {
        HttpUtils.doGet(HttpContant.URL + HttpContant.CityBycoordinate + "?cityName=" + cityName
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("getCityList", response.body().string()));
                    }
                });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        switch (event.getCls()) {
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                break;
            case "getCityList":
                Log.i("getCityList", event.getData().toString());
                break;
            case "getStoreInfo":
                LogUtil.e("getStoreInfo", event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){
                        mList = new ArrayList<>();
                        StoreListBean storeListBean = new Gson().fromJson(event.getData().toString(), StoreListBean.class);
                        mList.addAll(storeListBean.getData().getRecords());
                        mRecylerAdapter.addAll(mList);
                        mRecylerAdapter.notifyDataSetChanged();
                    }else {
                        TastyToast.makeText(getActivity(),object.getString("msg"),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mRecyclerView != null) {
            mRecyclerView.destroy();
            mRecyclerView = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_head_back_iv:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.food_city_tv:
                CityPicker.getInstance()
                        .setFragmentManager(getActivity().getSupportFragmentManager())
                        .enableAnimation(enable)
                        .setAnimationStyle(anim)
                        .setLocatedCity(null)
                        .setHotCities(hotCities)
                        .setOnPickListener(new OnPickListener() {
                            @Override
                            public void onPick(int position, City data) {
                                cityTv.setText(data == null ? "杭州" : data.getName());
//                                if (data != null) {
//                                    Toast.makeText(
//                                            getActivity().getApplicationContext(),
//                                            String.format("点击的数据：%s，%s", data.getName(), data.getCode()),
//                                            Toast.LENGTH_SHORT)
//                                            .show();
//                                }
                            }

                            @Override
                            public void onLocate() {
                                //开始定位，这里模拟一下定位
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        CityPicker.getInstance().locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS);
                                    }
                                }, 3000);
                            }
                        })
                        .show();
                break;
            case R.id.choose_region:
//                if (checkedbutton)
                if (checkedbutton == v.getId()) {
                    DismissAnimtion(mDownMuneContainer);
                    checkedbutton = -1;
                    return;
                } else {
                    showAnimtion(mDownMuneContainer, checkedbutton);
                    showItem(v.getId());
                    checkedbutton = v.getId();
                }

                break;
            case R.id.food_class_tv:
                if (checkedbutton == v.getId()) {
                    DismissAnimtion(mDownMuneContainer);
                    checkedbutton = -1;
                    return;
                } else {
                    showAnimtion(mDownMuneContainer, checkedbutton);
                    showItem(v.getId());
                    checkedbutton = v.getId();
                }
                break;
            case R.id.food_sort_tv:
                if (checkedbutton == v.getId()) {
                    DismissAnimtion(mDownMuneContainer);
                    checkedbutton = -1;
                    return;
                } else {
                    showAnimtion(mDownMuneContainer, checkedbutton);
                    showItem(v.getId());
                    checkedbutton = v.getId();
                }
                break;
        }
    }

    private void showItem(int id) {
        chooseFragmentById(id);
    }

    /**
     * 动画
     */
    private void showAnimtion(final View view, int checkedbutton) {
        Log.e("checkedbutton", checkedbutton + "");
        if (checkedbutton == -1) {
            AlphaAnimation alpha = new AlphaAnimation(0.0f, 1.0f);
            //@integer/abc_config_activityShortDur"
            alpha.setDuration(300);
            alpha.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    view.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animation animation) {

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            view.startAnimation(alpha);
        }
    }

    private void DismissAnimtion(final View view) {
        AlphaAnimation alpha = new AlphaAnimation(1.0f, 0.0f);
        //@integer/abc_config_activityShortDur"
        alpha.setDuration(300);
        alpha.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(alpha);
    }

    public void closeDownMenu() {
//        setBtnClose();
        DismissAnimtion(mDownMuneContainer);
//        mDownMuneContainer.setVisibility(View.GONE);
        checkedbutton = -1;
    }

    private void chooseFragmentById(int id) {
//        FragmentManager fm = getSupportFragmentManager();
//
//        // 开启事务
//        FragmentTransaction transaction = fm.beginTransaction();
//
//        // 加载左侧
//        transaction.replace(R.id.down_menu_container, MenuFragmentFactory.getFragment(id));
//
//        transaction.commit();
        /**------------------------闪屏解决------------------------------*/
        FragmentManager fm = getActivity().getSupportFragmentManager();

        // 开启事务
        FragmentTransaction transaction = fm.beginTransaction();

        Fragment fragment = fm.findFragmentByTag(id + "");

        boolean isShowOrAdd = true;

//        if (fragment == null) {
            isShowOrAdd = false;
            switch (id) {
                case R.id.choose_region:
                    // 地区
                    fragment = new PullBaseFragment();
                    if (!cityTv.getText().toString().equals("城市")){
//                        Bundle bundle2 = new Bundle();
//                        bundle2.putString("cityName",cityTv.getText().toString());
//                        fragment.setArguments(bundle2);
                        ((PullBaseFragment) fragment).regionStoreData(cityTv.getText().toString(),getActivity());
                    }
                    ((PullBaseFragment) fragment).setOnSetDataListener(new PullBaseFragment.OnSetDataListener() {
                        @Override
                        public void setData(String data1, String data2) {
                            Log.i("PullBaseFragment",data1+data2);
                            regionTv.setText(data2);
                            httpStoreInfo(cityTv.getText().toString(),regionTv.getText().toString(),classTv.getText().toString(),1);
                            closeDownMenu();
                        }
                    });
                    break;
                case R.id.food_class_tv:
                    // 食品分类
                    fragment = new CatalogueFragment();
                    Bundle bundle1 = new Bundle();
                    fragment.setArguments(bundle1);
                    ((CatalogueFragment) fragment).setOnSetDataListener(new CatalogueFragment.OnSetDataListener() {
                        @Override
                        public void setData(String data1) {

                            classTv.setText(data1);
                            closeDownMenu();
                            httpStoreInfo(cityTv.getText().toString(),regionTv.getText().toString(),classTv.getText().toString(),1);
                        }
                    });
                    break;
                case R.id.food_sort_tv:
                    // 排序
                    fragment = new SortFragment();
                    Bundle bundle3 = new Bundle();
                    fragment.setArguments(bundle3);
                    ((SortFragment) fragment).setOnSetDataListener(new SortFragment.OnSetDataListener() {
                        @Override
                        public void setData(String data1) {
                            sortTv.setText(data1);
                            closeDownMenu();
                            httpStoreInfo(cityTv.getText().toString(),regionTv.getText().toString(),classTv.getText().toString(),1);
                        }
                    });
                    break;
                default:
                    break;
            }
//        }
        if (mCurrentFragment != null) {
            transaction.hide(mCurrentFragment);
        }
        if (isShowOrAdd) {
            transaction.show(fragment);
//            fragment.onResume();
        } else {
            transaction.add(R.id.down_menu_container, fragment, id + "");
        }
        mCurrentFragment = fragment;
        // 加载左侧
//        transaction.replace(R.id.down_menu_container, MenuFragmentFactory.getFragment(id));

        transaction.commit();
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (cityTv.getText().toString().equals("城市")){
            regionTv.setEnabled(false);
            classTv.setEnabled(false);
            sortTv.setEnabled(false);
        }else {
            regionTv.setEnabled(true);
            classTv.setEnabled(true);
            sortTv.setEnabled(true);
        }
    }

    interface OnItemListener {
        void onItemClick(View view, int position,String data);
        void onItemAddress(View view,String address,String storeName);
    }

    static class FoodAdapter extends RecyclerHolder<StoreListBean.DataBean.RecordsBean> {


        private OnItemListener mItemListener;
        private ImageView storeImg;
        private TextView nameTv, classTv, addressTv;
        private RelativeLayout relativeLayout;
        private Button releaseBt;

        public FoodAdapter(View itemView, OnItemListener listener) {
            super(itemView);

            mItemListener = listener;

            storeImg = itemView.findViewById(R.id.food_img);
            nameTv = itemView.findViewById(R.id.food_store_name);
            classTv = itemView.findViewById(R.id.food_class);
            addressTv = itemView.findViewById(R.id.food_address);
            relativeLayout = itemView.findViewById(R.id.item_food_rl);
            releaseBt = itemView.findViewById(R.id.release_date_bt);

        }

        @Override
        public void onBindView(final StoreListBean.DataBean.RecordsBean dataBean) {
            Glide.with(storeImg.getContext()).load(dataBean.getPhoto_urls()).asBitmap().error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic).into(storeImg);
            nameTv.setText(dataBean.getName());
            String categories = "";
            for (int i = 0; i < dataBean.getCategories().size(); i++) {
                categories = categories+dataBean.getCategories().get(i)+"   ";
            }
            classTv.setText(categories);
            addressTv.setText(dataBean.getAddress());

            relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemListener.onItemClick(v,getAdapterPosition(),new Gson().toJson(dataBean));
                }
            });

            releaseBt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemListener.onItemAddress(v,dataBean.getAddress(),dataBean.getName());
                }
            });
        }
    }
}
